package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.serverUtils.ExcelUtil;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverEnchashment;
import com.ybkj.daijia.server.model.DriverLogin;
import com.ybkj.daijia.server.model.DriverRebateEnchashment;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverLoginService;
import com.ybkj.daijia.server.service.DriverRebateEnchashmentService;
import com.ybkj.daijia.server.service.DriverService;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "driverRebateenchashment")
public class DriverRebateEnchashmentController {

    private static final Logger logger = LoggerFactory.getLogger(DriverEnchashmentController.class);

    @Autowired
    private DriverService driverService;
    @Autowired
    private DriverRebateEnchashmentService driverRebateEnchashmentService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private DriverLoginService driverLoginService;

    /***
     * 跳转推荐奖励审核页面, 具体数据由js中ajax请求
     * @param param
     * @return
     */
    @RequestMapping(value = "extendList", method = RequestMethod.GET)
    public String list(String param) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("driverenchashment")) {
            return "driverenchashment/extendList";
        } else {
            throw new NoPermissionException();
        }

    }

    /***
     * 后台获取推荐奖励提现审核数据
     * @param param
     * @return
     */
    @RequestMapping(value = "listData", method = RequestMethod.GET)
    @ResponseBody
    public Page<DriverRebateEnchashment> listData(String param) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("driverenchashment")) {
            Page<DriverRebateEnchashment> queryAll = driverRebateEnchashmentService
                .queryByEmploy(null, param, Pager.getPage(), Pager.getLimit());
            return queryAll;
        } else {
            throw new NoPermissionException();
        }

    }

    /****
     * 后台审核记录接口
     * @param id
     * @param
     * @return
     * result turndown, success
     */
    @RequestMapping(value = "audit", method = RequestMethod.POST)
    public synchronized @ResponseBody
    Result<DriverRebateEnchashment> audit(
        @RequestParam("id") Long id,
        @RequestParam("result") String result) {
        Result<DriverRebateEnchashment> vo = new Result<DriverRebateEnchashment>();

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("driverenchashment")) {
            DriverRebateEnchashment driverEnchashment = driverRebateEnchashmentService.findOne(id);
            if (!driverEnchashment.getStatus().equals(DriverEnchashment.STATUS_WAIT)) {
                vo.setMessage("该记录已审核通过或驳回，不能重复操作");
                return vo;
            }

            Driver driver = driverService.findOne(driverEnchashment.getEmployId());

            driverRebateEnchashmentService.audit(driverEnchashment, driver, result);

            String detail = "【%s】审核了服务人员【" + driver.getUsername() + "】的提现申请";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            vo.setSuccess(true);
            return vo;
        } else {
            vo.setSuccess(false);
            vo.setMessage("您没有该权限");
            return vo;
        }
    }

    /***
     * 财务导出数据
     * @param param
     * @param req
     * @param response
     * @param session
     * @return
     * @throws IOException
     * @throws ParseException
     */
    @RequestMapping(value = "exportMoney", method = RequestMethod.GET)
    public @ResponseBody
    String exportOrder(
        @RequestParam(value = "param") String param,
        HttpServletRequest req, HttpServletResponse response, HttpSession session
    ) throws IOException, ParseException {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        List<DriverRebateEnchashment> content = new ArrayList<DriverRebateEnchashment>();
        if (principal.isCompanyType()) {
            content = driverRebateEnchashmentService.listByEmploy(null, param);
        } else {
            content = driverRebateEnchashmentService.listByEmploy(null, param);
        }
        List<List<String>> rowlist = new ArrayList<List<String>>();
        String[] head = new String[27];
        head[0] = ("状态");
        head[1] = ("姓名");
        head[2] = ("工号");
        head[3] = ("手机号");
        head[4] = ("申请金额");
        head[5] = ("申请时间");

        for (DriverRebateEnchashment de : content) {
            List<String> celllist = new ArrayList<String>();
            if (de.getStatus() == 0) {
                celllist.add("待审核");
            } else if (de.getStatus() == 1) {
                celllist.add("已同意");
            } else if (de.getStatus() == 2) {
                celllist.add("已驳回");
            }
            celllist.add(de.getEmployRealName());
            celllist.add(de.getEmployUserName());
            celllist.add(de.getEmployPhone());
            celllist.add(de.getOpRebateMoney().toString());
            SimpleDateFormat sf = new SimpleDateFormat("yy"
                + "yy-MM-dd HH:mm");
            String date = sf.format(de.getCreated());
            celllist.add(date);
            rowlist.add(celllist);
        }

        return ExcelUtil.createExcel(req, response, head, rowlist);
    }

    /***
     * 查看导出进度
     * @param session
     * @return
     */
    @RequestMapping(value = "exportMoneyProcess", method = RequestMethod.GET)
    public @ResponseBody
    Object exportOrderProcess(HttpSession session) {
        return session.getAttribute("exportZhuancheProcess");
    }

    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /***0
     * app 司机申请提现推荐奖励
     * @param employToken
     * @param money
     * @return
     */
    @RequestMapping(value = "applyEnchashment", method = RequestMethod.POST)
    public synchronized @ResponseBody
    ResultTransport applyEnchashment(String employToken, BigDecimal money) {
        logger.debug("recv employToken:{},money:{}", employToken, money);
        Setting oldsetting = settingUtils.get();

        //只有每个月第一天才能推荐奖励提现
        if (!employToken.equals("super") && 1 != Calendar.getInstance()
            .get(Calendar.DAY_OF_MONTH)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.CANT_ENCHASHMENT_IN_AFTER_FIRST_DAY);
        }
        if (StringUtils.isBlank(employToken) || null == money) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        if (money.compareTo(BigDecimal.ZERO) <= 0) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }
        DriverLogin driverLogin;
        if (employToken.equals("super")) {
            driverLogin = new DriverLogin();
            driverLogin.setDriverId(30L);
        } else {
            driverLogin = driverLoginService.selectByToken(employToken);

            if (null == driverLogin) {
                return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
            }

            if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
                return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
            }
        }
        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (driver.getRebateMoney().compareTo(money) == -1) {
            return ResultTransport
                .getErrorBy(ErrorConstantV4.EMPLOY_REBATE_ENCHASHMENT_MONEY_NOT_ENOUGH);
        }

        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }

        try {

            int result = driverService.updateByPrimaryKey(driver);

            if (result == 0) {
                return ResultTransport.getErrorBy(ErrorConstantV4.DRIVER_UPDATE_ERROR);
            }

            driverRebateEnchashmentService.apply(driver, money);
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver applyEnchashment error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }


    /**
     * 司机查看推荐奖励申请提现记录
     *
     * @param employToken
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping(value = "queryEnchashment", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport queryEnchashment(String employToken, Integer page, Integer limit) {

        logger.debug("recv employToken:{},page:{},limit:{}", employToken, page, limit);

        if (StringUtils.isBlank(employToken) || null == page || null == limit) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin;
        if (employToken.equalsIgnoreCase("super")) {
            driverLogin = new DriverLogin();
            driverLogin.setDriverId(30L);
        } else {
            driverLogin = driverLoginService.selectByToken(employToken);
            ;
        }

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (!employToken.equalsIgnoreCase("super") && System.currentTimeMillis() >= driverLogin
            .getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        try {

            Page<DriverRebateEnchashment> enchashments = driverRebateEnchashmentService
                .queryByEmploy(driverLogin.getDriverId(), null, page, limit);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(enchashments);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver queryEnchashment error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }
}

